package cdu.notFound.Dao.impl;

import cdu.notFound.Dao.OrderDao;
import cdu.notFound.model.Goods;
import cdu.notFound.model.Order;
import cdu.notFound.model.User;
import cdu.notFound.utils.DatabaseConnection;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    private Connection conn = null;
    private PreparedStatement pstmt = null;

    public OrderDaoImpl() {
        try {
            this.conn = new DatabaseConnection().getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public boolean doCreate(Order order){
        boolean flag = false;
        String sql = "INSERT INTO `order`(goods_id,user_id,date,message) VALUES (?,?,?,?)";
        try {
            this.pstmt = this.conn.prepareStatement(sql);
            this.pstmt.setInt(1,order.getGoodsId());
            this.pstmt.setInt(2,order.getUserId());
            Timestamp dateTime = new Timestamp(order.getDate().getTime());
            pstmt.setTimestamp(3, dateTime);
            pstmt.setString(4, order.getMessage());
            if (this.pstmt.executeUpdate() > 0) {
                flag = true;
            }
            this.pstmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }
    
    public List<Goods> findGoodsByUser(User user){
        int userId=user.getId();
        List<Goods> goods = new ArrayList<>();
        String sql = "select id,num,content,type_id,image,producter_id,price,create_date,name from `goods` where id=any(SELECT goods_id from `order`  where user_id=?)";
        try {
            this.pstmt = this.conn.prepareStatement(sql);
            this.pstmt.setInt(1,userId);
            ResultSet rs = this.pstmt.executeQuery();
            while (rs.next()) {
                Goods good = new Goods();
                good.setId(rs.getInt(1));
                good.setNum(rs.getInt(2));
                good.setContent(rs.getString(3));
                good.setType_id(rs.getInt(4));
                good.setImage(rs.getString(5));
                good.setProducter_id(rs.getInt(6));
                good.setPrice(rs.getFloat(7));
                Timestamp timeStamp=rs.getTimestamp(8);
                good.setName(rs.getString(9));
                Date date=new Date(timeStamp.getTime());
                good.setCreatDate(date);
                goods.add(good);
            }
            rs.close();this.pstmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return goods;
    }
    
	public void close(){
		if(this.conn != null){
			try{
				this.conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
